package com.zzb.codegenerator.config;

import com.zzb.codegenerator.utils.PropertiesUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 通过properties配置文件获取配置类
 * Created by zhangzhenbin on 2016/10/7.
 */
public class GeneratorConfigPropertiesFactory implements IGeneratorConfigFactory{
    @Override
    public GeneratorConfig build(String filename) {
        List<Field> fields = new ArrayList<>();
        CollectionUtils.addAll(fields, GeneratorConfig.class.getDeclaredFields());
        GeneratorConfig generatorConfig = new GeneratorConfig();
        Map<String , String > configMap = getConfigMap(filename);
        for (Field field : fields) {
            String fieldName = field.getName();
            String value = configMap.get(fieldName);
            if(StringUtils.isNotBlank(value)){
                try {
                    FieldUtils.writeDeclaredField(generatorConfig,fieldName,value,true);
                } catch (Exception e) {
                    System.err.println("写入配置项【"+fieldName+"="+value+"】错误");
                }
            }
        }


        return generatorConfig;
    }

    /**获取配置map*/
    public Map<String,String> getConfigMap(String filename){
        Map<String, String> configMap = PropertiesUtil.loadAllProperties("default.properties");
        configMap = PropertiesUtil.mergeProperties(configMap, filename,true);
        return configMap;
    }

}
